import {AfterViewInit, Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {fromEvent, Subject} from 'rxjs';
import {auditTime, takeUntil} from 'rxjs/operators';

@Component({
  selector: 'app-load-model',
  templateUrl: './load-model.component.html',
  styleUrls: ['./load-model.component.scss']
})
export class LoadModelComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('canvasRef') canvasRef: ElementRef;

  private _destroy$ = new Subject();

  constructor(private ngZone: NgZone) { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    import('./model-render').then(module => {
      this.ngZone.runOutsideAngular(_ => {
        const canvasEl = this.canvasRef.nativeElement as HTMLCanvasElement;
        const modelRender = new module.ModelRender(canvasEl);
        const render = () => {
          window.requestAnimationFrame(render);
          modelRender.render();
        };

        modelRender.initDisplay();
        modelRender.resizeDisplay();
        modelRender.initContent().then(() => {
          render();
        });

        fromEvent(window, 'resize')
          .pipe(
            auditTime(500),
            takeUntil(this._destroy$)
          )
          .subscribe(() => {
            modelRender.resizeDisplay();
          });
      })
    });
  }

  ngOnDestroy() {
    this._destroy$.next();
    this._destroy$.complete();
  }

}
